<?php
namespace App\Models\System;

use App\Exceptions\ApiException;
use App\Providers\LengthAwarePaginatorProvider;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\Enums\System\SysNotice\{NoticeType, Status};

/**
* 通知公告表 模型
* @create 2023-08-22 16:44:03
*/
class SysNoticeModel extends \App\Models\BaseModel {
    use HasFactory;


    const Table         = "sys_notice";
    const PrimaryKey    = "notice_id";
    public $timestamps  = true;

    static $Wheres = ['notice_id','notice_type','status'];     // 直接定义column, 默认where(column, '=', value)
    public function __construct($attributes = []) {
        parent::__construct($attributes);

        // static::$Wheres['notice_id'] = fn($q, $v) => $q->where(atn('notice_id'), '=', $v);
        static::$Wheres['create_by'] = fn($q, $v) => $q->where(atn('create_by'), 'like', "%{$v}%");
        static::$Wheres['notice_title'] = fn($q, $v) => $q->where(atn('notice_title'), 'like', "%{$v}%");
    }

    /** xxxx */
    // public function user() {
        // return $this->hasOne(User::class, 'id', 'uid');
    // }

    /** ========== 常用查询 ========== */
    static $Vo  = ['notice_id','notice_title','notice_type','cast(notice_content as char) as notice_content','status','create_by','create_time','update_by','update_time','remark'];
    static $Voi = ['*', ];


    public function scopeSelectVo(Builder $query): void {
        if (static::is_api()) {
            $query->select(atn(static::$Voi));
        } else {
            $query->selectRaw(join(',', static::$Vo));
        }
     }

    /**
     * 查询公告信息
     * 
     * @param $noticeId 公告ID
     * @return SysNoticeModel 公告信息
     */
    public function selectNoticeById(int $noticeId): SysNoticeModel {
        return throw_str(
            $this->selectVo()
                ->where(atn('notice_id'), '=', $noticeId)
                ->first()
            ?? "公告($noticeId)查找失败"
        );
    }

    /**
     * 查询公告列表
     * 
     * @param $notice 公告信息
     * @return SysNoticeModel[]|Collection 公告集合
     */
    public function selectNoticeList(array $notice=null): Collection {
        return $this->selectVo()
            ->wheres($notice, 'notice_title', 'notice_type', 'create_by')
            ->get()
            ;
    }

    /**
     * 新增公告
     * 
     * @param $notice 公告信息
     * @return 结果
     */
    public function insertNotice(array $notice): SysNoticeModel {
        $values = static::when(
                    $notice,
                    'notice_title',
                    'notice_type',
                    'notice_content',
                    'status',
                    'remark',
                    'create_by',
                );
        return throw_str(
            static::row_add($values)
        );
    }

    /**
     * 修改公告
     * 
     * @param $notice 公告信息
     * @return 结果
     */
    public function updateNotice(array $notice): int {
        $values = static::when(
                    $notice,
                    'notice_title',
                    'notice_type',
                    'notice_content',
                    'status',
                    'update_by',
                );
        return $this
                ->where(atn('notice_id'), '=', get_value($notice, 'notice_id'))
                ->update($values);
    }

    /**
     * 批量删除公告
     * 
     * @param $noticeId 公告ID
     * @return int 结果
     */
    public function deleteNoticeById($noticeId): int {
        return $this->deleteNoticeByIds([$noticeId]);
    }

    /**
     * 批量删除公告信息
     * 
     * @param $noticeIds 需要删除的公告ID
     * @return int 结果
     */
    public function deleteNoticeByIds(array $noticeIds): int {
        return $this
            ->whereIn('notice_id', $noticeIds)
            ->delete()
            ;
    }

    /** 根据NoticeId获取 */
    public function selectByNoticeId($notice_id): SysNoticeModel {
        $where = [['notice_id', '=', "{$notice_id}"]];
        return throw_str(
            static::row($where) ?? "数据($notice_id)为空~"
        );
    }


    /** 获取列表 @return SysNotice[]+paginator() */
    public function selectList(int|array $pag=1, array $param=[]): LengthAwarePaginatorProvider {
        return static::rows_pag($pag, [], fn($q)=>$q
                    // ->when(isset($param['notice_id']), fn($q)=>$q->where('notice_id', '=', $param['notice_id']))
                    ->wheres($param, 'notice_id','notice_type','status')
                    ->orderByDesc("notice_id")
        );
    }


    /** 插入数据 */
    public function insertData(array $data): SysNoticeModel {
        return throw_str(
            static::row_add([
                // 'notice_id'          => $data['notice_id'],
                'notice_title'          => $data['notice_title'],
                'notice_type'           => $data['notice_type'],
                'notice_content'        => $data['notice_content'] ?? '',
                'status'                => $data['status'] ?? '0',
                'create_by'             => $data['create_by'] ?? '',
                // 'create_time'        => $data['create_time'] ?? '',
                'update_by'             => $data['update_by'] ?? '',
                // 'update_time'        => $data['update_time'] ?? '',
                'remark'                => $data['remark'] ?? '',
            ])
        );
    }


    /** 更新数据 */
    public function updateData(int|array $idOrWhere, array $data): SysNoticeModel {
        $values = static::when(
                    $data, 
                    // 'notice_id',
                    'notice_title',
                    'notice_type',
                    'notice_content',
                    'status',
                    'create_by',
                    // 'create_time',
                    'update_by',
                    // 'update_time',
                    'remark',
                );
        return throw_str(
            static::row_update($idOrWhere, $values)
        );
    }


    /** 删除数据 */
    public function deleteData(int|array $idOrWhere): SysNoticeModel {
        return throw_str(
            static::row_delete($idOrWhere)
        );
    }



}